<?php
	
	require_once '../includes/Config.inc.php';
	
	$cfg = Config::getInstance('..');
	$facebook = $cfg->getFacebook();
	
	$myUid = isset($_POST['fb_sig_in_profile_tab']) ? $facebook->get_profile_user() : $facebook->require_login();
	
	$user = User::getUserFbID($myUid);
	
	$Smarty = $cfg->getSmarty();
	$now = time();
	
	if($now - $user->location_date > $cfg->geoloc_timeout) {
	
		$orange = new OrangeAPI($cfg->or_api_key);
		$resp = $orange->geoloc($user->phone);
	
		if ($resp->isValid()) {
		
			// Get latitude & longitude
			$long =  $resp->getLongitude();
			$lat = $resp->getLatitude();
		
			$user->longitude = $long;
			$user->latitude = $lat;
			$user->location_date = $now;
			$user->save();
		
			$Smarty->assign('longitude', $long);
			$Smarty->assign('latitude', $lat);		
			$Smarty->assign('errorCode', 'noError');
		}
		else {
			$errorCode = $resp->getStatusCode();
			$Smarty->assign('errorCode', $errorCode);
		}
	}
	elseif($user->longitude != 0 && $user->latitude != 0) {
		$Smarty->assign('longitude', $user->longitude);
		$Smarty->assign('latitude', $user->latitude);		
		$Smarty->assign('errorCode', 'noError');
	}
	else {
		$Smarty->assign('errorCode', 'error');
	}

	// load template
	$Smarty->assign('userid', $myUid);
	$Smarty->display('facebookTab.tpl');
?>
